package com.qili.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.controller.BaseController;
import com.qili.base.entity.CurrentUser;
import com.qili.core.annotation.Log;
import com.qili.core.shiro.Principal;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.base.BaseDict;
import com.qili.entity.exam.ExQuAnswer;
import com.qili.entity.exam.ExQuestion;
import com.qili.entity.exam.ExTree;
import com.qili.entity.exam.dto.ExQuestionDTO;
import com.qili.entity.it.Tree;
import com.qili.entity.supplier.SupplierProjectPubNotice;
import com.qili.entity.sys.SysLog;
import com.qili.entity.sys.SysUser;
import com.qili.exception.MyException;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseDictService;
import com.qili.service.exam.ExQuAnswerService;
import com.qili.service.exam.ExQuestionService;
import com.qili.service.jc.JcProjectService;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.UserDatabase;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * @Author:zhangxiaopeng
 * @Description: 试题库
 * @Date:10:46 2021/8/9
 */
@Controller
@Slf4j
@RequestMapping("/ex/question")
public class exQuestionController extends BaseController {

    @Autowired
    ExQuestionService exQuestionService;
    @Autowired
    ExQuAnswerService exQuAnswerService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    private SysLogMapper logMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private JcProjectService jcProjectService;
    @Autowired
    private SupervisorFileService supervisorFileService;
    @Autowired
    private SysLogMapper sysLogMapper;

    /**
     * 试题库页面
     *
     * @return
     */
    @GetMapping(value = "/stkIndex")
    @RequiresPermissions("zh:stk")
    public String stkList(Model model) {
        //试题题型
        List<BaseDict> sttx = baseDictService.selectByTypeCode(DictTypes.STTX.getType());
        model.addAttribute("sttx", sttx);
        return "synthesize/itemBankIndex";
    }

    /**
     * 回收站页面
     *
     * @return
     */
    @GetMapping(value = "/recycleBin")
    public String recycleBin() {
        return "synthesize/recycleBin";
    }

    /**
     * 试题库新增页面
     *
     * @return
     */
    @GetMapping(value = "/stkAdd")
    public String stkAdd(Model model) {
        //试题题型
        List<BaseDict> sttx = baseDictService.selectByTypeCode(DictTypes.STTX.getType());
        model.addAttribute("sttx", sttx);
        //试题分类
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtGroupid("STFL");
        List<BaseDict> stfl = baseDictService.select(baseDict);
        model.addAttribute("stfl", stfl);
        //试题难度
        List<BaseDict> stnd = baseDictService.selectByTypeCode(DictTypes.STND.getType());
        model.addAttribute("stnd", stnd);
        return "synthesize/itemBankAdd";
    }

    /**
     * 试题分类-树显示
     * @return
     */
    @GetMapping(value = "/selectTypeClassifyQu")
    @ResponseBody
    public ReType selectTypeClassify(String identifying){
        List<Map<String,Object>> treeDtoList = null;
        try {
            BaseDict baseDict = new BaseDict();
            baseDict.setBadtTypecode("STFL");
            List<BaseDict> sjfl = baseDictService.select(baseDict); // 查询的第一级
            treeDtoList = new ArrayList<>();
            // 添加选择分类，什么也不选择
            if (StringUtil.isNotBlank(identifying)){
                Map<String,Object> defaultData = new HashMap<>();
                defaultData.put("id","");
                defaultData.put("title","请选择分类");
                defaultData.put("children","");
                treeDtoList.add(defaultData);
            }
            for (BaseDict dict : sjfl) {
                Map<String,Object> resultMap = new HashMap<>();
                resultMap.put("id",dict.getBadtCode());
                resultMap.put("title",dict.getBadtName());
                // 查询当前结点的子节点
                BaseDict bd = new BaseDict();
                bd.setBadtGroupid("STFL");
                bd.setBadtTypecode(dict.getBadtCode());
                List<BaseDict> erSjfl = baseDictService.select(bd); // 当前结点下的子节点集合
                List<Map<String,String>> tempErTree = new ArrayList<>();
                if (erSjfl != null && erSjfl.size() > 0){
                    for (BaseDict baseDict2 : erSjfl) {
                        Map<String, String> stringMap = new HashMap<>();
                        stringMap.put("id",baseDict2.getBadtCode());
                        stringMap.put("title",baseDict2.getBadtName());
                        stringMap.put("children","");
                        tempErTree.add(stringMap);
                    }
                }
                resultMap.put("children",tempErTree);
                treeDtoList.add(resultMap);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ReType.success(200,"成功",treeDtoList);
    }

    /**
     * 试题库修改页面
     *
     * @return
     */
    @GetMapping(value = "/stkUpdate")
    public String stkUpdate(Model model, ExQuestion eq) {
        //试题
        ExQuestion exQuestion = exQuestionService.selectOne(eq);
        model.addAttribute("eq", exQuestion);
        //答案
        Example ecj = new Example(ExQuAnswer.class);
        Example.Criteria ccj = ecj.createCriteria();
        ccj.andEqualTo("quId", eq.getQuId());
        ecj.setOrderByClause("serial ASC");
//        ExQuAnswer quAnswer=new ExQuAnswer();
        List<ExQuAnswer> exq = exQuAnswerService.selectByExample(ecj);
        model.addAttribute("exq", exq);
        model.addAttribute("index", exq.size());
        //试题题型
        List<BaseDict> sttx = baseDictService.selectByTypeCode(DictTypes.STTX.getType());
        model.addAttribute("sttx", sttx);
        //试题分类
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtGroupid("STFL");
        List<BaseDict> stfl = baseDictService.select(baseDict);
        model.addAttribute("stfl", stfl);
        //试题难度
        List<BaseDict> stnd = baseDictService.selectByTypeCode(DictTypes.STND.getType());
        model.addAttribute("stnd", stnd);
        return "synthesize/itemBankUpdate";
    }

    /**
     * 试题库列表查询
     *
     * @param dto
     * @param model
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/stkList")
    @ResponseBody
    public ReType stkList(ExQuestionDTO dto, Model model, int page, int limit) {
        List<ExQuestionDTO> stkList = null;
        //试题分类查询当前目录和下级目录数据
        if (!"STFL".equals(dto.getQuCategory())) {
            if (StringUtil.isNotBlank(dto.getQuCategory())) {
                List<String> list = new ArrayList<>();
                list.add(dto.getQuCategory());
                ExTree exTree = new ExTree();
                exTree.setId(dto.getQuCategory());
                List<ExTree> treeList = selectTreeList(exTree);
                for (int i = 0; i < treeList.size(); i++) {
                    list.add(treeList.get(i).getId());
                }
                dto.setTreeList(list);
            }
        }
        Page<ExQuestionDTO> tPage = PageHelper.startPage(page, limit);
        try {
            stkList = exQuestionService.selectExQuestion(dto);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), stkList);
    }

    /**
     * 回收站查询
     *
     * @param dto
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/selectRecycleBin")
    @ResponseBody
    public ReType selectRecycleBin(ExQuestionDTO dto, int page, int limit) {
        List<ExQuestionDTO> stkList = null;
        Page<ExQuestionDTO> tPage = PageHelper.startPage(page, limit);
        dto.setState("000");
        try {
            stkList = exQuestionService.selectExQuestion(dto);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), stkList);
    }

    /**
     * 试题库新增、编辑
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "insertSt")
    @ResponseBody
    @RequiresRoles("ksgly")
    public JsonUtil insertSt(ExQuestionDTO dto) {
        JsonUtil json = new JsonUtil();
        try {
            if (StringUtils.isNotBlank(dto.getQuId())) {
                insertFileLog("试题更新","参数："+dto.getContent(),"UPDATE");
                //修改
                dto.setModifyBy(CommonUtil.getUserId());
                dto.setModifyDate(DateUtil.getCurrentDateString());
                json = isNotNull(json, dto);
                if (StringUtil.isNotBlank(json.getMsg())) {
                    return json;
                }
                //试题
                if (exQuestionService.updateByPrimaryKeySelective(dto) > 0) {
                    //试题答案
                    updateExQuAnswer(dto);
                    json.setFlag(true);
                    return json;
                }
            } else {
                insertFileLog("试题新增","参数："+dto.getContent(),"ADD");
                //新增
                dto.setQuId(IdUtil.simpleUUID());
                dto.setCreateBy(CommonUtil.getUserId());
                dto.setCreateDate(DateUtil.getCurrentDateString());
                json = isNotNull(json, dto);
                if (StringUtil.isNotBlank(json.getMsg())) {
                    return json;
                }
                //试题
                if (exQuestionService.insert(dto) > 0) {
                    //试题答案
                    insertExQuAnswer(dto);
                    json.setFlag(true);
                    return json;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        json.setMsg("保存失败！");
        json.setFlag(false);
        return json;
    }

    /**
     * @param json
     * @param dto
     * @Description:验证必填项不能为空
     * @Date:13:31 2021-09-14
     */
    public JsonUtil isNotNull(JsonUtil json, ExQuestionDTO dto) {
        List<ExQuAnswer> exq = new ArrayList<>();
        //不同试题类型不同字段 001 单选  002 多选 003 判断  004 填空  005 问答
        if ("001".equals(dto.getQuType())) {
            exq = dto.getExDxList();
            for (int i = 0; i < exq.size(); i++) {
                if (StringUtil.isBlank(exq.get(0).getIsItRight())) {
                    json.setMsg("请选择正确答案！");
                    json.setFlag(false);
                    return json;
                }
            }
        } else if ("002".equals(dto.getQuType())) {
            exq = dto.getExDuoxList();
            int j = 0;
            for (int i = 0; i < exq.size(); i++) {
                if (StringUtil.isNotBlank(exq.get(i).getIsItRight())) {
                    j = j + 1;
                }
            }
            if (j == 0) {
                json.setMsg("请选择正确答案！");
                json.setFlag(false);
                return json;
            }
        } else if ("003".equals(dto.getQuType())) {
            exq = dto.getExPdList();
            for (int i = 0; i < exq.size(); i++) {
                if (StringUtil.isBlank(exq.get(0).getIsItRight())) {
                    json.setMsg("请选择正确答案！");
                    json.setFlag(false);
                    return json;
                }
            }
        } else if ("004".equals(dto.getQuType())) {
            exq = dto.getExTkList();
            for (int i = 0; i < exq.size(); i++) {
                if (StringUtil.isBlank(exq.get(i).getAnswerContent())) {
                    json.setMsg("答案不可为空！");
                    json.setFlag(false);
                    return json;
                }
            }
        } else if ("005".equals(dto.getQuType())) {
            exq = dto.getExWdList();
            for (int i = 0; i < exq.size(); i++) {
                if (StringUtil.isBlank(exq.get(i).getAnswerContent())) {
                    json.setMsg("答案不可为空！");
                    json.setFlag(false);
                    return json;
                }
            }
        }
        json.setFlag(true);
        return json;
    }

    /**
     * 修改试题答案
     *
     * @param dto
     * @return
     */
    public void updateExQuAnswer(ExQuestionDTO dto) {
        List<ExQuAnswer> exq = new ArrayList<>();
        //不同试题类型不同字段 001 单选  002 多选 003 判断  004 填空  005 问答
        if ("001".equals(dto.getQuType())) {
            exq = dto.getExDxList();
        } else if ("002".equals(dto.getQuType())) {
            exq = dto.getExDuoxList();

        } else if ("003".equals(dto.getQuType())) {
            exq = dto.getExPdList();

        } else if ("004".equals(dto.getQuType())) {
            exq = dto.getExTkList();
        } else if ("005".equals(dto.getQuType())) {
            exq = dto.getExWdList();
        }
        if (exq != null && exq.size() > 0) {
            //单选、判断处理
            if ("001".equals(dto.getQuType()) || "003".equals(dto.getQuType())) {
                for (int i = 0; i < exq.size(); i++) {
                    if (StringUtils.isNotBlank(exq.get(i).getAnswerContent())) {
                        if ((exq.get(i).getAnswerContent()).equals(exq.get(0).getIsItRight())) {
                            exq.get(i).setIsRight("1");
                        } else {
                            exq.get(i).setIsRight("");
                        }
                    }
                    exq.get(i).setSerial(i);
                    updates(exq.get(i), dto.getQuId());
                }
            } else if ("002".equals(dto.getQuType())) {
                //多选处理
                for (int i = 0; i < exq.size(); i++) {
                    if (StringUtils.isNotBlank(exq.get(i).getAnswerContent())) {
                        if ((exq.get(i).getAnswerContent()).equals(exq.get(i).getIsItRight())) {
                            exq.get(i).setIsRight("1");
                        } else {
                            exq.get(i).setIsRight("");
                        }
                    }
                    exq.get(i).setSerial(i);
                    updates(exq.get(i), dto.getQuId());
                }
            } else {
                for (int i = 0; i < exq.size(); i++) {
                    exq.get(i).setSerial(i);
                    updates(exq.get(i), dto.getQuId());
                }
            }
        }
    }

    //只新增了问题没有添加答案 修改时没有id走新增反之走修改
    public void updates(ExQuAnswer exq, String id) {
        exq.setQuId(id);
        exq.setModifyBy(CommonUtil.getUserId());
        exq.setModifyDate(DateUtil.getCurrentDateString());
        if (StringUtils.isNotBlank(exq.getQuAnswerId())) {
            exQuAnswerService.updateByPrimaryKeySelective(exq);
        } else {
            exq.setQuAnswerId(IdUtil.simpleUUID());
            exQuAnswerService.insert(exq);
        }
    }

    /**
     * 新增试题答案
     *
     * @param dto
     * @return
     */
    public void insertExQuAnswer(ExQuestionDTO dto) {
        List<ExQuAnswer> exq = new ArrayList<>();
        //不同试题类型不同字段 001 单选  002 多选 003 判断  004 填空  005 问答
        if ("001".equals(dto.getQuType())) {
            exq = dto.getExDxList();
        } else if ("002".equals(dto.getQuType())) {
            exq = dto.getExDuoxList();
        } else if ("003".equals(dto.getQuType())) {
            exq = dto.getExPdList();
        } else if ("004".equals(dto.getQuType())) {
            exq = dto.getExTkList();
        } else if ("005".equals(dto.getQuType())) {
            exq = dto.getExWdList();
        }
        if (exq != null && exq.size() > 0) {
            //单选、判断处理   和答案相同的是正确的
            if ("001".equals(dto.getQuType()) || "003".equals(dto.getQuType())) {
                for (int i = 0; i < exq.size(); i++) {
                    if (StringUtils.isNotBlank(exq.get(i).getAnswerContent())) {
                        if (exq.get(i).getAnswerContent().equals(exq.get(0).getIsItRight())) {
                            exq.get(i).setIsRight("1");
                        } else {
                            exq.get(i).setIsRight("");
                        }
                    }
                    exq.get(i).setSerial(i);
                    insets(exq.get(i), dto.getQuId());
                }
            } else if ("002".equals(dto.getQuType())) {
                //多选处理   和答案相同的是正确的
                for (int i = 0; i < exq.size(); i++) {
                    if (StringUtils.isNotBlank(exq.get(i).getAnswerContent())) {
                        if (exq.get(i).getAnswerContent().equals(exq.get(i).getIsItRight())) {
                            exq.get(i).setIsRight("1");
                        } else {
                            exq.get(i).setIsRight("");
                        }
                    }
                    exq.get(i).setSerial(i);
                    insets(exq.get(i), dto.getQuId());
                }
            } else {
                for (int i = 0; i < exq.size(); i++) {
                    exq.get(i).setIsRight("1");
                    exq.get(i).setSerial(i);
                    insets(exq.get(i), dto.getQuId());
                }
            }
        }
    }

    public void insets(ExQuAnswer exq, String id) {
        exq.setQuId(id);
        exq.setQuAnswerId(IdUtil.simpleUUID());
        exq.setCreateBy(CommonUtil.getUserId());
        exq.setCreateDate(DateUtil.getCurrentDateString());
        exQuAnswerService.insert(exq);
    }

    /**
     * 数据还原
     *
     * @param eq
     * @return
     */
    @GetMapping(value = "/updateHy")
    @ResponseBody
    public JsonUtil updateHy(ExQuestion eq) {
        JsonUtil json = new JsonUtil();
        // 查询删除之前的状态
        ExQuestion exQuestion = exQuestionService.selectByPrimaryKey(eq.getQuId());
        if (!StringUtil.isBlank(exQuestion.getReductionType())){
            eq.setStatus(exQuestion.getReductionType());
        }
        eq.setCreateBy(CommonUtil.getUserId());
        eq.setCreateDate(DateUtil.getCurrentDateString());
        if (exQuestionService.updateByPrimaryKeySelective(eq) > 0) {
            json.setFlag(true);
            return json;
        }
        json.setFlag(false);
        return json;
    }

    /**
     * 试题库删除（改状态）/批量提交/数据还原
     *
     * @param eq
     * @return
     */
    @GetMapping(value = "/updateSt")
    @ResponseBody
    @RequiresRoles("ksgly")
    public JsonUtil updateSt(ExQuestion eq, String[] ids, String state) {
        JsonUtil json = new JsonUtil();
        try {
            //ids有值走批量
            if (ids != null && ids.length > 0 && StringUtils.isNotBlank(state)) {
                // 需要先判断删除前的类型
                for (String id : ids) {
                    ExQuestion exQuestion = exQuestionService.selectByPrimaryKey(id);
                    String type = "";
                    if (!StringUtil.isBlank(exQuestion.getStatus())){
                        type = exQuestion.getStatus();
                    }
                    // 封装参数
                    Map map = new HashMap();
                    map.put("id", id);
                    map.put("status", state);
                    map.put("modifyBy", CommonUtil.getUserId());
                    map.put("modifyDate", DateUtil.getCurrentDateString());
                    // 2021年11月24日 新增还原之前的类型
                    map.put("reductionType", type);
                    exQuestionService.deleteStsN(map);
                }
            } else {
                eq.setModifyBy(CommonUtil.getUserId());
                eq.setModifyDate(DateUtil.getCurrentDateString());
                exQuestionService.updateByPrimaryKeySelective(eq);
            }
            json.setFlag(true);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(false);
            return json;
        }
    }

    /**
     * 批量删除（改状态）
     *
     * @param ids
     * @return
     */
    public int deleteSts(ExQuestion eq, String[] ids, String state) {
        Map map = new HashMap();
        map.put("ids", ids);
        map.put("status", state);
        map.put("modifyBy", CommonUtil.getUserId());
        map.put("modifyDate", DateUtil.getCurrentDateString());
        // 2021年11月24日 新增还原之前的类型
        map.put("reductionType", eq.getReductionType());
        return exQuestionService.deleteSts(map);
    }

    /**
     * 回收站  全部彻底删除
     *
     * @return
     */

    @GetMapping(value = "/deleteAll")
    @ResponseBody
    public JsonUtil deleteAll() {
        JsonUtil json = new JsonUtil();
        try {
            ExQuestion eq = new ExQuestion();
            eq.setStatus("000");
            List<ExQuestion> select = exQuestionService.select(eq);
            deleteAllL(select);
            json.setFlag(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(false);
            json.setMsg("删除失败");
        }
        return json;
    }
    /**
     * 回收站  删除
     * @return
     */
    /**
     * @param ids
     * @Author:Zhangshuo
     * @Description:删除回收站项目数据
     * @Date:20:23 2020-12-11
     */
    @ApiOperation(value = "/deleteQuestionFromRecycle", httpMethod = "POST", notes = "从回收站中删除项目")
    @PostMapping(value = "deleteQuestionFromRecycle")
    @ResponseBody
    public JsonUtil deleteProjects(@RequestBody String[] ids) {
        try {
            if (ids == null || ids.length <= 0) {
                return JsonUtil.error("参数有误");
            }
            for (String id : ids) {
                ExQuestion exQuestion = exQuestionService.selectByPrimaryKey(id);
                insertFileLog("从回收站中删除试题","参数："+exQuestion.getContent(),"DEL");
            }
            int AiFlag = exQuestionService.deleteProjectsFromRecycle(ids);
            if (AiFlag <= 0) {
                return JsonUtil.error("删除失败。");
            }
            return JsonUtil.sucess("删除成功。");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("删除失败，" + e.getMessage());
        }
    }

    /**
     * 回收站  批量还原
     *
     * @return
     */
    @PostMapping(value = "/hyAll")
    @ResponseBody
    public JsonUtil hyAll(@RequestBody String[] ids) {
        try {
            if (ids == null || ids.length <= 0) {
                return JsonUtil.error("参数有误");
            }
            // 判断当前删除之前是什么状态
            for (String id : ids) {
                ExQuestion exQuestion = exQuestionService.selectByPrimaryKey(id);
                String type = "001";
                if (!StringUtil.isBlank(exQuestion.getReductionType())){
                    type = exQuestion.getReductionType();
                }
                // 去执行更新操作 2021年11月24日14:44:39 新加
                exQuestionService.hyAll(id, type);
            }

//            int AiFlag = exQuestionService.hyAll(ids);
            return JsonUtil.sucess("还原成功。");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("还原失败，" + e.getMessage());
        }
    }

    @GetMapping("deleteFromRecycle")
    @ResponseBody
    public JsonUtil deleteFromRecycle(String quId) {
        try {
            if (StringUtil.isBlank(quId)) {
                return JsonUtil.error("参数有误");
            }
            ExQuestion exQuestion = exQuestionService.selectByPrimaryKey(quId);
            int count = exQuestionService.deleteFromRecycle(quId);
            if (count > 0) {
                insertFileLog("从回收站中删除试题","参数："+exQuestion.getContent(),"DEL");
                return JsonUtil.sucess("删除成功");
            }
            return JsonUtil.error("删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("删除失败"+e.getMessage());
        }
    }

    public void deleteAllL(List<ExQuestion> select) {
        if (select != null) {
            if (select.size() > 0) {
                for (int i = 0; i < select.size(); i++) {
                    ExQuestion exQuestion = select.get(i);
                    SysLog log = new SysLog();
                    log.setCreateTime(new Date());
                    log.setType("DEL");
                    log.setText("从回收站中删除试题");
                    log.setParam("参数：" + exQuestion.getContent());
                    log.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateTimeString()));
                    CurrentUser currentUser = Principal.getCurrentUse();
                    log.setUserName(currentUser.getUsername());
                    logMapper.insert(log);
                    exQuestionService.delete(exQuestion);

                }
            }

        }

    }

    /**
     * 查询试题分类
     *
     * @param tree
     * @return
     */
    @GetMapping(value = "/selectTree")
    @ResponseBody
    public List<ExTree> selectTree(ExTree tree) {
        //查询出第一级
        List<ExTree> trList = exQuestionService.selectTree(tree);
        List<ExTree> list = new ArrayList<>();
        list = selectTreeList(trList.get(0));
        if (list != null) {
            trList.get(0).setChildren(list);
        }
        return trList;
    }


    /**
     * 递归查出试题分类数据
     *
     * @param tree
     * @return
     */
    public List<ExTree> selectTreeList(ExTree tree){
        List<ExTree> list =exQuestionService.selectTrees(tree);
        if(list!=null&&list.size()>0) {
            for (int i = 0; i < list.size(); i++) {
                List<ExTree> list1 = selectTreeList(list.get(i));
                list.get(i).setChildren(list1);
            }
        }
        return list;
    }

    /**
     * @param request
     * @Description:新增试题分类节点
     * @Date:15:21 2021-09-03
     */
    @GetMapping(value = "insertTree")
    @ResponseBody
    public JsonUtil insertTree(HttpServletRequest request) {
        JsonUtil js = new JsonUtil();
        String id = request.getParameter("parentRoleId");
        String name = request.getParameter("name");
        String treeId = IdUtil.simpleUUID();
        Map map = new HashMap();
        map.put("badtName", name);
        map.put("badtTypecode", id);
        map.put("badtCode", treeId);
        map.put("badtGroupid", "STFL");
        int i = 0;
        i = exQuestionService.insertTree(map);
        if (i > 0) {
            js.setFlag(true);
            js.setData(treeId);
        } else {
            js.setFlag(false);
        }
        return js;
    }

    /**
     * 修改试题分类节点
     *
     * @param request
     * @return
     */
    @GetMapping(value = "updateTree")
    @ResponseBody
    public JsonUtil updateTree(HttpServletRequest request) {
        JsonUtil js = new JsonUtil();
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        Map map = new HashMap();
        map.put("name", name);
        map.put("id", id);
        int i = 0;
        i = exQuestionService.updateTree(map);
        if (i > 0) {
            js.setFlag(true);
        } else {
            js.setFlag(false);
        }
        return js;
    }

    /**
     * 删除试题分类节点
     *
     * @param request
     * @return
     */
    @GetMapping(value = "deleteTree")
    @ResponseBody
    @Log(desc = "删除试题分类节点", type = Log.LOG_TYPE.DEL)
    public JsonUtil deleteTree(HttpServletRequest request) {
        JsonUtil js = new JsonUtil();
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtCode(id);
        baseDict.setBadtGroupid("STFL");
        try {
            int i = 0;
            if (StringUtil.isNotBlank(id)) {
                i = baseDictService.delete(baseDict);
            } else {
                i = 0;
            }
            if (i > 0) {
                js.setFlag(true);
            } else {
                js.setMsg("系统异常");
                js.setFlag(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return js;
    }

    /**
     * 删除前判断是否被引用
     *
     * @param request
     * @return
     */
    @GetMapping(value = "deleteHint")
    @ResponseBody
    public JsonUtil deleteHint(HttpServletRequest request) {
        JsonUtil js = new JsonUtil();
        String id = request.getParameter("id");
        ExQuestion exQuestion = new ExQuestion();
        exQuestion.setQuCategory(id);
        List<ExQuestion> exList = exQuestionService.select(exQuestion);
        //判断是否被引用
        if (exList != null && exList.size() > 0) {
            js.setMsg("该分类被引用不可删除");
            js.setFlag(false);
            return js;
        } else {
            //判断下面节点是否被引用
            ExTree tree = new ExTree();
            tree.setId(id);
            List<ExTree> list = exQuestionService.selectTrees(tree);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    ExQuestion eq = new ExQuestion();
                    eq.setQuCategory(list.get(i).getId());
                    List<ExQuestion> eqList = exQuestionService.select(eq);
                    //判断是否被引用
                    if (eqList != null && eqList.size() > 0) {
                        js.setMsg("该分类下节点被引用不可删除");
                        js.setFlag(false);
                        return js;
                    }
                }
            }
        }
        js.setFlag(true);
        return js;
    }

    /**
     * @param request
     * @param response
     * @param eq
     * @Description:导出试题
     * @Date:16:12 2021-09-10
     */
    @GetMapping(value = "/exportStk")
    @RequiresRoles("ksgly")
    public void exportStk(HttpServletRequest request, HttpServletResponse response, ExQuestion eq) throws IOException, ParseException {
        String fileName = "试题" + DateUtil.getCurrentDateNoSpliter();
        HashMap map = new HashMap();
        //试题
        ExQuestion exQuestion = exQuestionService.selectOne(eq);
        //题目
        String name = parseHtml(exQuestion.getContent());
        map.put("name", name);
        //试题解析
        map.put("jx", parseHtml(exQuestion.getAnalysis()));
        //试题类型
        BaseDict base = DictUtil.getDictByCode(DictTypes.STTX, exQuestion.getQuType());
        map.put("sttx", base.getBadtName());
        //答案
        Example ecj = new Example(ExQuAnswer.class);
        Example.Criteria ccj = ecj.createCriteria();
        ccj.andEqualTo("quId", eq.getQuId());
        ecj.setOrderByClause("serial ASC");
        List<ExQuAnswer> exq = exQuAnswerService.selectByExample(ecj);
        StringJoiner answer = new StringJoiner(",");
        if ("001".equals(exQuestion.getQuType()) || "002".equals(exQuestion.getQuType())) {
            for (int i = 0; i < exq.size(); i++) {
                if (StringUtil.isNotBlank(exq.get(i).getIsRight())) {
                    answer.add(exq.get(i).getAnswerContent());
                }
                exq.get(i).setAnswerAnalysis(parseHtml(exq.get(i).getAnswerAnalysis()));
            }
        } else if ("003".equals(exQuestion.getQuType())) {
            for (int i = 0; i < exq.size(); i++) {
                if (StringUtil.isNotBlank(exq.get(i).getIsRight())) {
                    answer.add(exq.get(i).getAnswerContent());
                }
            }
        } else if ("004".equals(exQuestion.getQuType())) {
            for (int i = 0; i < exq.size(); i++) {
                if (StringUtil.isNotBlank(exq.get(i).getIsRight())) {
                    answer.add(exq.get(i).getAnswerContent());
                }
                exq.get(i).setAnswerContent(parseHtml(exq.get(i).getAnswerAnalysis()));
                exq.get(i).setAnswerAnalysis("");
            }
        } else if ("005".equals(exQuestion.getQuType())) {
            for (int i = 0; i < exq.size(); i++) {
                if (StringUtil.isNotBlank(exq.get(i).getIsRight())) {
                    answer.add(exq.get(i).getAnswerContent());
                }
                exq.get(i).setAnswerContent("问答题");
                exq.get(i).setAnswerAnalysis("");
            }
        }
        map.put("answer", answer);
        map.put("daLists", exq);
        try {
            ExcelExportUtilEX.exportExcel(response, map, fileName, "ST001");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //处理富文本数据
    public String parseHtml(String html) {
        if (html == null || html == "") {
            return html = "空";
        } else {
            html = html.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
            return html;
        }
    }

    //日志
    public void insertFileLog(String text,String param,String type ) {
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType(type);
        sysLog.setText(text);
        sysLog.setParam(param);
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        CurrentUser currentUser = Principal.getCurrentUse();
        sysLog.setUserName(currentUser.getUsername());
        sysLogMapper.insert(sysLog);
    }

}
